package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.UserResourceCreateCmd;
import com.baoyouqun.domain.Enum.ResourceTypeEnum;
import com.baoyouqun.domain.Query.UserResourceQuery;
import com.baoyouqun.domain.UpdateCmd.UserResourceUpdateCmd;
import com.baoyouqun.domain.VO.UserResourceVO;
import com.baoyouqun.entity.UserResource;
import com.baoyouqun.mapper.UserResourceMapper;
import com.baoyouqun.service.UserResourceService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class UserResourceServiceImpl extends ServiceImpl<UserResourceMapper, UserResource> implements UserResourceService {

    @Resource
    private UserResourceMapper userResourceMapper;

    @Override
    public SingleResponse<UserResourceVO> create(UserResourceCreateCmd cmd) {
        UserResource entity =
                ConvertUtils.copyBean(cmd, UserResource.class);
        boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        UserResourceVO vo =
                ConvertUtils.copyBean(entity, UserResourceVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(UserResourceUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        UserResource oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, UserResource.class);
        boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public UserResourceVO selectById(String id) {
        UserResource entity = baseMapper.selectById(id);
        UserResourceVO vo =
                ConvertUtils.copyBean(entity, UserResourceVO.class);
        return vo;
    }

    @Override
    public IPage<UserResourceVO> pageVo(UserResourceQuery query) {
        IPage<UserResource> page = new Page<UserResource>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<UserResource>());
        Page<UserResourceVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<UserResourceVO> records = ConvertUtils.copyBeanList(page.getRecords(), UserResourceVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    /**
     * 通用方法：处理资源关联表（删旧插新）
     */
    @Override
    public void handleResource(String userId, List<UserResourceCreateCmd> resourceList) {
        if (resourceList == null || StringUtil.isBlank(userId)) {
            return;
        }
        // 构造新关联数据
        List<UserResource> resourceEntities = resourceList.stream()
                .map(resource -> {
                    UserResource entity = new UserResource();
                    entity.setUserId(userId);
                    entity.setResourceTypeEnum(resource.getResourceTypeEnum());
                    entity.setName(resource.getName());
                    return entity;
                }).collect(Collectors.toList());
        // 批量插入新关联
        if (!resourceEntities.isEmpty()) {
            saveBatch(resourceEntities);
        }
    }

    @Override
    public void deleteByUserId(String userId) {
        if (StringUtil.isBlank(userId)) {
            return;
        }
        remove(new LambdaQueryWrapper<UserResource>().eq(UserResource::getUserId, userId));
    }

    @Override
    public Map<String, List<String>> getUserResourcesMap(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }

        // 查询所有用户的资源
        List<UserResource> resources = list(
                new LambdaQueryWrapper<UserResource>()
                        .in(UserResource::getUserId, userIds)
                        .eq(UserResource::getResourceTypeEnum, ResourceTypeEnum.OWN) // 1表示资源类型
        );

        // 按用户ID分组
        Map<String, List<UserResource>> userResourcesMap = resources.stream()
                .collect(Collectors.groupingBy(UserResource::getUserId));

        // 转换为用户ID到资源描述列表的映射
        Map<String, List<String>> result = new HashMap<>();
        for (String userId : userIds) {
            List<UserResource> userResources = userResourcesMap.get(userId);
            if (CollUtil.isEmpty(userResources)) {
                result.put(userId, Collections.emptyList());
            } else {
                // 提取前3个资源的描述
                List<String> descriptions = userResources.stream()
                        .limit(3)
                        .map(UserResource::getName)
                        .collect(Collectors.toList());
                result.put(userId, descriptions);
            }
        }

        return result;
    }

    @Override
    public Map<String, List<String>> getUserNeedsMap(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }

        // 查询所有用户的需求
        List<UserResource> needs = list(
                new LambdaQueryWrapper<UserResource>()
                        .in(UserResource::getUserId, userIds)
                        .eq(UserResource::getResourceTypeEnum, ResourceTypeEnum.NEED) // 1表示资源类型
        );

        // 按用户ID分组
        Map<String, List<UserResource>> userNeedsMap = needs.stream()
                .collect(Collectors.groupingBy(UserResource::getUserId));

        // 转换为用户ID到需求描述列表的映射
        Map<String, List<String>> result = new HashMap<>();
        for (String userId : userIds) {
            List<UserResource> userNeeds = userNeedsMap.get(userId);
            if (CollUtil.isEmpty(userNeeds)) {
                result.put(userId, Collections.emptyList());
            } else {
                // 提取前3个需求的描述
                List<String> descriptions = userNeeds.stream()
                        .limit(3)
                        .map(UserResource::getName)
                        .collect(Collectors.toList());
                result.put(userId, descriptions);
            }
        }

        return result;
    }

    @Override
    public List<UserResourceVO> selectByUserId(String userId) {
        List<UserResource> resources = list(
                new LambdaQueryWrapper<UserResource>()
                        .eq(UserResource::getUserId, userId)
        );
        return ConvertUtils.copyBeanList(resources, UserResourceVO.class);
    }

    @Override
    public Map<String, Integer> countByUserIds(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyMap();
        }

        // 按用户ID分组统计资源数量（包含需求和拥有资源）
        List<Map<String, Object>> countList = baseMapper.selectMaps(new QueryWrapper<UserResource>()
                .in("user_id", userIds)
                .groupBy("user_id")
                .select("user_id, count(1) as count"));

        // 转换为Map并补全所有用户ID（默认0）
        Map<String, Integer> resultMap = userIds.stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        userId -> 0
                ));

        countList.forEach(map -> {
            String userId = (String) map.get("user_id");
            Integer count = Integer.parseInt(map.get("count").toString());
            resultMap.put(userId, count);
        });

        return resultMap;
    }

    @Override
    public Collection<String> selectUserIdsByTypeAndResourceIds(ResourceTypeEnum resourceType, Set<String> resourceIds) {
        // 边界条件处理：资源类型为空或资源ID列表为空，返回空列表
        if (resourceType == null || resourceIds == null || resourceIds.isEmpty()) {
            return List.of();
        }

        // 构建查询条件：匹配资源类型 + 资源ID在列表中
        LambdaQueryWrapper<UserResource> wrapper = new LambdaQueryWrapper<UserResource>()
                .eq(UserResource::getResourceTypeEnum, resourceType) // 匹配资源类型（NEED/OWN）
                .in(UserResource::getName, resourceIds) // 资源ID在指定列表中
                .select(UserResource::getUserId); // 只查询用户ID字段（优化性能）

        // 执行查询并提取用户ID，去重（避免同一用户关联同一资源多次）
        return baseMapper.selectList(wrapper).stream()
                .map(UserResource::getUserId)
                .distinct() // 去重
                .collect(Collectors.toList());
    }
}